package com.example.demo0331.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


@RestController
public class FileController {

    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public String upload(String name, MultipartFile file, HttpServletRequest request) throws IOException {
        System.out.println("文件大小:" + file.getSize());
        System.out.println("文件类型:" + file.getContentType());
        saveFile(file, request.getServletContext().getRealPath("/upload/")); // 存放文件在tomcat目录下upload文件夹
        return name + file.getOriginalFilename();
    }

    public void saveFile(MultipartFile upFile, String path) throws IOException {
        System.out.println("文件存放在:" + path);
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdir();
        }
        File file = new File(path + upFile.getOriginalFilename());
        upFile.transferTo(file);
    }
}
